package main

import (
	"archive/zip"
	"io"
	"os"
	"path/filepath"
)

func main() {
	if len(os.Args) == 1 {
		print("path cannot be empty")
		return
	}
	f := os.Args[1]

	err := decompress(f, f+".dir")
	if err != nil {
		println("zip failed,the reason is " + err.Error())
	} else {
		print("unzip file " + f + " success ")
	}

}

func decompress(zipFile, dest string) error {
	reader, err := zip.OpenReader(zipFile)
	if err != nil {
		return err
	}
	defer reader.Close()

	for _, f := range reader.File {
		fpath := filepath.Join(dest, f.Name)
		println("unzip file:" + fpath)
		if f.FileInfo().IsDir() {
			os.MkdirAll(fpath, os.ModePerm)
		} else {
			if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
				return err
			}
			inFile, err := f.Open()
			if err != nil {
				return err
			}
			defer inFile.Close()
			outfile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
			if err != nil {
				return err
			}
			defer outfile.Close()

			_, err = io.Copy(outfile, inFile)
			if err != nil {
				return err
			}

		}

	}

	return nil
}
